package chat;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author: zlz
 * @date: 2021/9/12 15:46
 * @description:
 * @since: JDK1.8
 */
public class ChatServerHandler extends SimpleChannelInboundHandler<String> {
    // GlobalEventExecutor.INSTANCE是全局的事件执行器，是一个单例
    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HHH:mm:ss");

    // 表示channel处于就绪状态，提示上线
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        // 将该客户加入聊天的信息推送给其他在线的客户端
        // 该方法将channelGroup中的所有channel遍历，并发送消息
        channelGroup.writeAndFlush("[ 客户端 ]" + channel.remoteAddress() + "上线了" + sdf.format(new Date()) + "\n");
        // 将当前channel添加到channelGroup
        channelGroup.add(channel);
        System.out.println(channel.remoteAddress() + "上线了");
    }

    // 处于不活动状态，用于提示离线
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channelGroup.writeAndFlush("[ 客户端 ]" + channel.remoteAddress() + "下线了" + "\n");
        System.out.println(channel.remoteAddress() + "下线了");
        System.out.println("channelGroup Size = " + channelGroup.size());
    }

    // 读取数据
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
        // 获取到当前channel
        Channel channel = channelHandlerContext.channel();
        channelGroup.forEach(ch -> {
            if (channel != ch) {
                ch.writeAndFlush("[ 客户端 ]" + channel.remoteAddress() + "发送了消息：" + s + "\n");
            } else {
                // 回显自己发送的消息
                ch.writeAndFlush("[ 自己 ] 发送了消息：" + s + "\n");
            }
        });
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        // 关闭通道
        ctx.close();
    }
}
